package com.lagou.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * 定义全局过滤器，会对所有路由生效
 */
@Slf4j
@Component
@ConditionalOnProperty(prefix = "lagou.gateway.out.standard", name = "enable", havingValue = "true")
public class BlackListFilter implements GlobalFilter, Ordered {


    private static class TimedRecord {
        private Long recordTime;
        private int count = 0;

        public Long getRecordTime() {
            return recordTime;
        }

        public void setRecordTime(Long recordTime) {
            this.recordTime = recordTime;
        }

        public int getCount() {
            return count;
        }

        public void setCount(int count) {
            this.count = count;
        }
    }

    /**
     * 每分钟同IP同请求URI,限制请求20次
     */

    @Value("${ipLimitReqPerMinThreshold:20}")
    public int ipLimitReqPerMinThreshold;
    private static Map<String, TimedRecord> limitBlackIps = new HashMap<>();

    /**
     * 过滤器核心方法
     *
     * @param exchange 封装了request和response对象的上下文
     * @param chain    网关过滤器链（包含全局过滤器和单路由过滤器）
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 思路：获取客户端ip，判断是否在黑名单中，在的话就拒绝访问，不在的话就放行
        // 从上下文中取出request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 从request对象中获取客户端ip 和 uri
        String clientIp = request.getRemoteAddress().getHostString();
        String uri = request.getURI().getPath();
        String key = clientIp + uri;

        if (limitBlackIps.containsKey(key)){
            TimedRecord timedRecord = limitBlackIps.get(key);
            long now = System.currentTimeMillis();
            if (timedRecord.getCount() + 1 > ipLimitReqPerMinThreshold && now - timedRecord.getRecordTime() > 60000){

                // 拒绝访问，返回
                response.setStatusCode(HttpStatus.SEE_OTHER); // 303状态码
                log.debug("=====>IP:" + clientIp + " 1min内请求超限，将被拒绝访问！");
                String data = "Request be denied!";
                DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                return response.writeWith(Mono.just(wrap));
            }else {
                timedRecord.setCount(timedRecord.getCount() + 1);
                limitBlackIps.put(key, timedRecord);
            }
        }

        // 合法请求，放行，执行后续的过滤器
        return chain.filter(exchange);
    }


    /**
     * 返回值表示当前过滤器的顺序(优先级)，数值越小，优先级越高
     *
     * @return
     */
    @Override
    public int getOrder() {
        return FilterOrder.LIMIT_BLACK_IP_FILTER_ORDER;
    }
}
